package com.gsbelarus.gedemin.salary.adapter;

import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.entity.model.GdMsgModel;
import com.gsbelarus.gedemin.salary.util.ExtractStringHelper;

import java.util.ArrayList;
import java.util.List;

import io.realm.RealmResults;

public class GdMsgRecyclerViewAdapter extends RecyclerView.Adapter<GdMsgRecyclerViewAdapter.RecyclerItemViewHolder> {

    private RealmResults<GdMsgModel> gdMsgDataSet;
    private RealmResults<GdMsgModel> gdMsgDataSetFiltrated;
    private SparseBooleanArray selectedItems;
    private OnItemListener mItemClickListener;
    private Context context;

    private String textFilter;
    private GdMsgModel.Sender senderFilter;

    public class RecyclerItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
        TextView subjectTextView;
        TextView dateTextView;
        TextView commentTextView;
        ImageView avatarImageView;

        public RecyclerItemViewHolder(View itemView) {
            super(itemView);
            subjectTextView = (TextView) itemView.findViewById(R.id.txt_subject);
            dateTextView = (TextView) itemView.findViewById(R.id.txt_date);
            commentTextView = (TextView) itemView.findViewById(R.id.txt_comment);
            avatarImageView = (ImageView) itemView.findViewById(R.id.image_view_avatar);
            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (mItemClickListener != null)
                mItemClickListener.onItemClick(v, getLayoutPosition());
        }

        @Override
        public boolean onLongClick(View v) {
            return mItemClickListener == null || mItemClickListener.onItemLongClick(v, getLayoutPosition());
        }
    }

    public interface OnItemListener {
        void onItemClick(View view, int position);

        boolean onItemLongClick(View view, int position);
    }

    public void setOnItemClickListener(final OnItemListener mItemClickListener) {
        this.mItemClickListener = mItemClickListener;
    }

    public GdMsgRecyclerViewAdapter(Context context, RealmResults<GdMsgModel> gdMsgDataSet) {
        this.context = context;
        this.gdMsgDataSet = gdMsgDataSet;
        this.gdMsgDataSetFiltrated = gdMsgDataSet;
        selectedItems = new SparseBooleanArray();
    }

    @Override
    public RecyclerItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.gdmsg_recycler_item, viewGroup, false);
        return new RecyclerItemViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(RecyclerItemViewHolder viewHolder, int position) {
        GdMsgModel gdMsg = gdMsgDataSetFiltrated.get(position);

        String status = ExtractStringHelper.getGdMsgRequestStatus(gdMsg);
        String subject = ExtractStringHelper.getGdMsgRequestSubject(gdMsg);

        String data = ExtractStringHelper.getGdMsgData(gdMsg);
        if (data != null && !data.isEmpty()) {
            data += ". ";
        }

        viewHolder.subjectTextView.setText(subject);
        viewHolder.commentTextView.setText(status + data + gdMsg.getComment());

        viewHolder.itemView.setActivated(selectedItems.get(position, false));

        if (viewHolder.itemView.isActivated()) {
            viewHolder.avatarImageView.setImageResource(R.mipmap.ic_check_white_36dp);
            ((GradientDrawable) viewHolder.avatarImageView.getBackground()).setColor(context.getResources().getColor(R.color.light_gray));
        } else {
            if (gdMsg.getSender() == GdMsgModel.Sender.SERVER) {
                viewHolder.avatarImageView.setImageResource(R.mipmap.ic_arrow_right_white_36dp);
            } else {
                viewHolder.avatarImageView.setImageResource(R.mipmap.ic_arrow_left_white_36dp);
            }

            switch (gdMsg.getRequestStatus()) {
                case SUCCESS:
                    ((GradientDrawable) viewHolder.avatarImageView.getBackground()).setColor(context.getResources().getColor(R.color.debit_color));
                    break;
                case UNKNOWN:
                    ((GradientDrawable) viewHolder.avatarImageView.getBackground()).setColor(context.getResources().getColor(R.color.light_gray));
                    break;
                case ERROR:
                case REJECTED:
                    ((GradientDrawable) viewHolder.avatarImageView.getBackground()).setColor(context.getResources().getColor(R.color.credit_color));
                    break;
            }
        }

        if (!gdMsg.isUnread()) {
            viewHolder.subjectTextView.setTypeface(null, Typeface.NORMAL);
            viewHolder.dateTextView.setTypeface(null, Typeface.NORMAL);
            viewHolder.dateTextView.setTextColor(context.getResources().getColor(R.color.gray));
        } else {
            viewHolder.subjectTextView.setTypeface(null, Typeface.BOLD);
            viewHolder.dateTextView.setTypeface(null, Typeface.BOLD);
            viewHolder.dateTextView.setTextColor(context.getResources().getColor(R.color.blue));
        }

        viewHolder.dateTextView.setText(ExtractStringHelper.getGdMsgFormattedTimestamp(gdMsg));
    }

    @Override
    public int getItemCount() {
        return gdMsgDataSetFiltrated.size();
    }

    public boolean isItemChecked(int position) {
        return selectedItems.valueAt(position);
    }

    public GdMsgModel getItem(int position) {
        return gdMsgDataSetFiltrated.get(position);
    }

    public int getSelectedItemCount() {
        return selectedItems.size();
    }

    public List<Integer> getSelectedItems() {
        List<Integer> selectedItemsUid = new ArrayList<>();
        for (int i = 0; i < selectedItems.size(); i++) {
            selectedItemsUid.add(gdMsgDataSetFiltrated.get(selectedItems.keyAt(i)).getUid());
        }
        return selectedItemsUid;
    }

    public void toggleSelection(int pos) {
        if (selectedItems.get(pos, false)) {
            selectedItems.delete(pos);
        } else {
            selectedItems.put(pos, true);
        }
        notifyItemChanged(pos);
    }

    public void setSelection(int pos) {
        selectedItems.put(pos, true);
        notifyItemChanged(pos);
    }

    public void clearSelections() {
        selectedItems.clear();
        notifyDataSetChanged();
    }

    public void notifyDataSetChangedWithFilters() {
        if (textFilter != null && !textFilter.isEmpty())
            this.gdMsgDataSetFiltrated = gdMsgDataSet.where().contains("gdMsgString", textFilter.toLowerCase(), false).findAllSorted("timestamp", false);
        else
            this.gdMsgDataSetFiltrated = gdMsgDataSet;

        if (senderFilter != null)
            this.gdMsgDataSetFiltrated = gdMsgDataSetFiltrated.where().equalTo("senderIndex", senderFilter.ordinal()).findAllSorted("timestamp", false);
        notifyDataSetChanged();
    }

    public String getTextFilter() {
        return textFilter;
    }

    public void setTextFilter(String textFilter) {
        this.textFilter = textFilter;
    }

    public GdMsgModel.Sender getSenderFilter() {
        return senderFilter;
    }

    public void setSenderFilter(GdMsgModel.Sender senderFilter) {
        this.senderFilter = senderFilter;
    }
}